"use client";
import { useEffect, useRef, useState } from "react";

import MaxWidthWrapper from "./MaxWidthWrapper";
import Phone from "./Phone";
import { useInView } from "framer-motion";
import { cn } from "@/lib/utils";

const PHONES = [
  "/testimonials/1.jpg",
  "/testimonials/2.jpg",
  "/testimonials/3.jpg",
  "/testimonials/4.jpg",
  "/testimonials/5.jpg",
  "/testimonials/6.jpg",
];


function splitArray<T>(array: Array<T>, numParts: number) {
  const result: Array<Array<T>> = [];
  for (let i = 0; i < array.length; i++) {
    const index = i % numParts;
    if (!result[index]) {
      result[index] = [];
    }
    result[index].push(array[i]);
  }
  return result;
}


// 每一列
function ReviewColumn({
  reviews,
  className,
  reviewClassName,
  msPerPixel = 0,
}: {
  reviews: string[];
  className?: string;
  reviewClassName?: (reviewIndex: number) => string;
  msPerPixel?: number;
}) {
  // 每一个列的ref
  const columnRef = useRef<HTMLDivElement | null>(null);
  const [cloumnHeight, setCloumnHeight] = useState(0);
  const duration = `${cloumnHeight * msPerPixel}ms`;

  useEffect(() => {
    // 监听每一列是否出现
    if (!columnRef.current) return;

    // 创建一个监听事件
    const resizeObserver = new ResizeObserver(() => {
      setCloumnHeight(columnRef.current?.offsetHeight ?? 0);
    });
    // 注册
    resizeObserver.observe(columnRef.current);

    return () => {
      // 页面卸载的时候取消监听事件
      resizeObserver.disconnect();
    };
  }, []);

  return (
    <div
      ref={columnRef}
      className={cn("animate-marquee space-y-8 py-4", className)}
      style={{ "--marquee-duration": duration } as React.CSSProperties}
    >
      {reviews.concat(reviews).map( (imgSrc, reviewIndex) => (
        <Review key={reviewIndex} className={reviewClassName?.(reviewIndex % reviews.length)} imgSrc={imgSrc} />
      ))}
    </div>
  );
}

interface ReviewProps extends React.HTMLAttributes<HTMLDivElement> {
  imgSrc: string;
  className?: string;
}

// 每一列单个
function Review ({imgSrc, className, ...props}: ReviewProps) {
  // 每一个动画延迟时间
  const POSSIBLE_ANIMATION_DELAYS = ['0s', '0.1s', '0.2s','0.3s','0.4s','0.5s']
  const animationDelay = POSSIBLE_ANIMATION_DELAYS[Math.floor(Math.random() * POSSIBLE_ANIMATION_DELAYS.length)]
  return <div {...props} className={cn(
    'animate-fade-in rounded-[2.25rem] bg-white p-6 opacity-0 shadow-xl shadow-slate-900/5', className
  )}
  style={{ animationDelay }}
  >
    <Phone imgSrc={imgSrc}/>
  </div>
}

function ReviewGrid() {
  const containerRef = useRef<HTMLDivElement | null>(null);
  const isInView = useInView(containerRef, { once: true, amount: 0.4 });
  const columns = splitArray(PHONES, 3);
  const columns1 = columns[0];
  const columns2 = columns[1];
  const columns3 = splitArray(columns[2], 2);

  return (
    <div
      ref={containerRef}
      className="relative -mx-4 mt-16 grid h-[49rem] max-h-[150vh] grid-col-1 items-start 
    gap-8 overflow-hidden px-4 sm:mt-20 md:grid-cols-2 lg:grid-cols-3"
    >
      {isInView ? (
        <>
          <ReviewColumn  
            reviews={[...columns1, ...columns2,...columns3.flat()]} 
            reviewClassName={(reviewIndex) => cn({
              'md:hidden': reviewIndex >= columns1.length + columns3[0].length, 
              "lg:hidden" : reviewIndex > columns1.length,
            })}
            msPerPixel={10}
          />

          <ReviewColumn  
            reviews={[...columns2,...columns3[1]]} 
            className='hidden md:block'
            reviewClassName={(reviewIndex) => reviewIndex >= columns2.length ? "lg:hidden" : ""}
            msPerPixel={15}
          />

          <ReviewColumn  
            reviews={columns3.flat()} 
            className='hidden md:block'
            reviewClassName={(reviewIndex) => reviewIndex >= columns2.length ? "lg:hidden" : ""}
            msPerPixel={20}
          />
        </>
      ) : null}

      <div className="pointer-events-none absolute inset-x-0 top-0 h-32 bg-gradient-to-b from-slate-100"></div>
      <div className="pointer-events-none absolute inset-x-0 bottom-0 h-32 bg-gradient-to-t from-slate-100"></div>
      
    </div>
  );
}

export function Reviews() {
  return (
    <MaxWidthWrapper className="relative max-w-3xl">
      <img
        aria-hidden="true"
        src="/what-people-are-buying.png"
        className="absolute select-none hidden xl:block -left-48 top-1/3"
      />

      <ReviewGrid />
    </MaxWidthWrapper>
  );
}
